package org.springcloud.plugin.common.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springcloud.plugin.common.constant.DiscoveryConstant;
import org.springcloud.plugin.common.util.JsonUtil;
import org.springcloud.plugin.common.util.StringUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.UnknownHttpStatusCodeException;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Author yanggld
 * @Date 2020/2/5-17:37
 * @Description resttemplate错误处理器
 */
@Slf4j
public class RestErrorHandler extends DefaultResponseErrorHandler {
	private String cause;

	@Override
	public void handleError(ClientHttpResponse response) throws IOException {
		// 这里绝对不能关闭InputStream
		InputStream inputStream = response.getBody();
		cause = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8);
		log.error("*************************************");
		log.error("resttemplate error: {}",cause);
		HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
		if (statusCode == null) {
			throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
					response.getHeaders(), getResponseBody(response), getCharset(response));
		}
		if (StringUtils.isNotEmpty(cause)) {
			JSONObject jsonObject = JSONObject.parseObject(cause);
			String statusText = jsonObject.getString("message");
			HttpHeaders headers = response.getHeaders();
			byte[] body = getResponseBody(response);
			Charset charset = getCharset(response);
			switch (statusCode.series()) {
				case CLIENT_ERROR:
					throw HttpClientErrorException.create(statusCode, statusText, headers, body, charset);
				case SERVER_ERROR:
					throw HttpServerErrorException.create(statusCode, statusText, headers, body, charset);
				default:
					throw new UnknownHttpStatusCodeException(statusCode.value(), statusText, headers, body, charset);
			}
		}
	}

	public String getCause() {
		return cause;
	}
}
